<template>
  <div class="custom-quality-engineering-container page-common-layout">
    <div class="screen-conditions-container">
      <a-select
        showSearch
        :filter-option="filterOption"
        v-model="condition.tenantCode"
        :loading="projectLoading"
        placeholder="请选择项目"
        @change="changeProject($event)"
        class="project-select"
      >
        <a-select-option
          :value="item.proCode"
          v-for="item in projectSoucre"
          :key="item.uuid"
        >
          {{ item.proName }}
        </a-select-option>
      </a-select>
      <a-select
        showSearch
        :filter-option="filterOption"
        placeholder="请选择责任主体"
        v-model="condition.orgCode"
        class="project-select"
      >
        <a-select-option
          :value="item.orgCode"
          v-for="item in orgSource"
          :key="item.uuid"
        >
          {{ item.orgName }}
        </a-select-option>
      </a-select>
      <a-select
        showSearch
        :filter-option="filterOption"
        placeholder="请选择任务状态"
        v-model="condition.taskStatus"
      >
        <a-select-option value="0"> 待发布 </a-select-option>
        <a-select-option value="1"> 资料提交 </a-select-option>
        <a-select-option value="2"> 待评分 </a-select-option>
        <a-select-option value="3"> 已完成 </a-select-option>
      </a-select>
      <div class="group-button">
        <a-button class="cu-btn-primary" icon="search" @click="search()">
          查询
        </a-button>
        <a-button class="cu-btn-filter" icon="reload" @click="reset()">
          重置
        </a-button>
      </div>
    </div>
    <div class="table-container">
      <div class="header" header="任务分配">
        <div>
          <a-button
            v-if="addAuth"
            @click="gotoAdd()"
            class="cu-btn-primary margin-bottom-xs"
            icon="plus"
            v-action:rwfp_add
          >
            新增
          </a-button>
          <a-button @click="gotoNotInvolve()">
            不涉及项配置
          </a-button>
        </div>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="taskName" title="任务名称"> </vxe-column>
          <vxe-column field="proName" title="项目名称"> </vxe-column>
          <vxe-column field="modelName" title="评价标准名称"> </vxe-column>
          <vxe-column field="orgCodeNames" title="责任主体"> </vxe-column>
          <vxe-column title="状态">
            <template #default="{ row }">
              <div :class="[checkStatusClass(row), 'status-text']">
                {{ checkStatusName(row) }}
              </div>
            </template>
          </vxe-column>
          <vxe-column field="deadline" title="截止时间"> </vxe-column>
          <vxe-column
            field="operate"
            width="220"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  v-for="(item, index) in row.normalBtns"
                  :key="index"
                  @click="eventDispacth(item.event, row)"
                  :class="[item.label == '删除' && 'danger']"
                >
                  {{ item.label }}
                </a-button>
                <a-popover
                  v-if="row.popoverBtns.length > 0"
                  overlayClassName="table-more-btns-popover"
                  placement="bottom"
                  :getPopupContainer="() => $el"
                >
                  <template slot="content">
                    <div
                      class="popover-btn"
                      v-for="(popBtn, index) in row.popoverBtns"
                      :key="index"
                      @click="eventDispacth(popBtn.event, row)"
                    >
                      {{ popBtn.label }}
                    </div>
                  </template>
                  <a-button type="link">...</a-button>
                </a-popover>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <addModal
      :visible.sync="addModalVisible"
      :parameter="dataSoucre"
    ></addModal>
    <!-- 查看页面 -->
    <viewModal
      :visible.sync="viewModalVisible"
      :soucre="dataSoucre"
      @cancel="handelCancel()"
      :key="viewModalKey"
    ></viewModal>
    <!-- 任务配置页面 -->
    <taskConfigModal
      :visible.sync="taskConfigModalVisible"
      :soucre="dataSoucre"
      :key="taskConfigKey"
      @ok="handelOk()"
      @cancel="handelCancel()"
    ></taskConfigModal>
    <!-- 不涉及配置页面 -->
    <notInvolveAdd
      :visible.sync="notInvolveAddVisible"
      @ok="handelOk()"
      @cancel="handelCancel()"
      :key="notInvolveAddKey"
    ></notInvolveAdd>
    <notInvolveView
      :visible.sync="notInvolveViewVisible"
      @cancel="handelCancel()"
      :key="notInvolveViewKey"
    ></notInvolveView>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
// 新增;
import addModal from "./components/addModal";
// 查看
import viewModal from "./components/viewModal";
// 任务配置
import taskConfigModal from "./components/taskConfigModal";
// 不涉及配置、新增
import notInvolveAdd from "./components/notInvolveAdd";
// 不涉及配置、查看
import notInvolveView from "./components/notInvolveView";
import { downLoadBatchFileByArraybuffer } from "@/utils/TopVUI";
import { getPZGCProList } from "@/api/qualityEngineering";
export default {
  components: {
    addModal,
    viewModal,
    taskConfigModal,
    notInvolveAdd,
    notInvolveView,
  },
  data() {
    return {
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      //新增弹窗
      addModalVisible: false,
      dataSoucre: {
        text: "",
        id: "",
      },
      //查看
      viewModalVisible: false,
      viewModalKey: "view_modal_01",
      //任务配置
      taskConfigModalVisible: false,
      taskConfigKey: "task_config_01",
      //不涉及配置
      notInvolveAddVisible: false,
      notInvolveAddKey: "add_01",
      notInvolveViewVisible: false,
      notInvolveViewKey: "view_01",
      modalKey: 0,
      //项目下拉框
      projectSoucre: [],
      projectLoading: false,
      //标段
      orgSource: [],
      orgLoading: false,
      condition: {
        //项目
        tenantCode: undefined,
        //标段
        orgCode: undefined,
        //状态
        taskStatus: undefined,
      },
      //新增权限
      addAuth: false,
      //不涉及项权限
      auth: {},
    };
  },
  mounted() {
    this.getProjectData();
  },
  methods: {
    handelOk() {
      this.viewModalVisible = false;
      this.taskConfigModalVisible = false;
      this.notInvolveAddVisible = false;
      this.notInvolveViewVisible = false;
      this.getTableData();
    },
    handelCancel() {
      this.viewModalVisible = false;
      this.taskConfigModalVisible = false;
      this.notInvolveAddVisible = false;
      this.notInvolveViewVisible = false;
      this.getTableData();
    },
    changeProject() {
      this.condition.orgCode = undefined;
      this.getData();
    },

    //查询项目下拉框
    getProjectData() {
      this.projectLoading = true;
      return new Promise((resolve, reject) => {
        getPZGCProList({ type: 1 })
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            this.condition.tenantCode =
              this.projectSoucre?.[0]?.proCode ?? undefined;
            if (!this.condition.tenantCode) {
              return;
            }
            this.getData();
            resolve();
          })
          .catch((_) => {
            this.condition.tenantCode = undefined;
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {
            this.projectLoading = false;
          });
      });
    },
    //查询标段下拉框
    getOrgList() {
      this.orgLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode = "" } = this.condition;
        axios
          .get(
            `/mdata/sysOrgExtend/getOrgExtendListByQX?tenantCode=${tenantCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.orgSource = res?.data || [];
            resolve();
          })
          .catch((_) => {
            this.orgSource = [];
            reject();
          })
          .finally((_) => {
            this.orgLoading = false;
          });
      });
    },
    //查询新增权限
    getTaskAddAuth() {
      let { tenantCode = "" } = this.condition;
      axios
        .get(
          `/probusiness/qeTaskAllocation/addAuth?tenantCode=${tenantCode}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.addAuth = res?.data;
        })
        .catch((_) => {
          this.addAuth = false;
        });
    },
    //查询不涉及项权限
    getNotAuth() {
      let { tenantCode = "" } = this.condition;
      axios
        .get(
          `/probusiness/qeNew/buttonAuth?tenantCode=${tenantCode}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.auth = res.data;
        })
        .catch((_) => {
          this.auth = {};
        });
    },
    getData() {
      Promise.all([
        this.getNotAuth(),
        this.getOrgList(),
        this.getTaskAddAuth(),
        this.getTableData(),
      ])
        .then()
        .finally((_) => {});
    },
    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    reset() {
      this.condition.orgCode = undefined;
      this.condition.taskStatus = undefined;
      this.search();
    },

    //发布考核
    release(row) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "您确定发布所选内容?",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          axios
            .get(
              `/probusiness/qeTaskAllocation/submitData?id=${row.uuid}`,
              {},
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              let { data } = res;
              if (data.statusCode === 200 || data === 1) {
                that.$message.success("发布成功", 1.5);
                that.getTableData();
              } else {
                that.$message.error(data.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //不涉及配置
    gotoNotInvolve() {
      if (this.auth.addNotContain) {
        this.notInvolveAddKey = Date.now();
        this.notInvolveAddVisible = true;
      }
      if (this.auth.viewNotContain) {
        this.notInvolveViewVisible = true;
      }
    },

    //任务配置
    gotoTaskConfig(row) {
      this.taskConfigKey = Date.now();
      this.dataSoucre = row;
      this.taskConfigModalVisible = true;
    },
    //新增
    gotoAdd() {
      this.modalKey = Date.now();
      this.dataSoucre = {
        text: "新增",
      };
      this.addModalVisible = true;
    },
    //编辑
    gotoEdit(row) {
      this.modalKey = Date.now();
      this.dataSoucre = {
        text: "编辑",
        ...row,
      };
      this.addModalVisible = true;
    },
    //查看
    gotoDetail(row) {
      this.viewModalKey = Date.now();
      this.dataSoucre = row;
      this.viewModalVisible = true;
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$get(`/probusiness/qeTaskAllocation/deleteData?id=${row.uuid}`)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //资料下载
    dataDownload(row) {
      let { uuid, taskName } = row;
      console.log(row);
      axios
        .get(`/probusiness/qeTaskAllocation/downloadFileZip?uuid=${uuid}`, {
          apiType: "file",
          responseType: "arraybuffer",
        })
        .then((res) => {
          downLoadBatchFileByArraybuffer(res, taskName);
        })
        .catch((_) => {});
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { taskStatus = "", tenantCode = "", orgCode = "" } = this.condition;
      axios
        .post(
          `/probusiness/qeTaskAllocation/getList?pageNo=${page}&pageSize=${pageSize}`,
          {
            tenantCode,
            taskStatus,
            orgCode,
            resourse: "",
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.tableData = res.data?.rows || [];
          this.pager.total = res.data?.totalCount || 0;
          this.tableData.forEach((v) => {
            if (v.taskStatus != 0) {
              this.$set(v, "zlxz", true);
            } else {
              this.$set(v, "zlxz", false);
            }
            let { normal = [], popover = [] } = this.filterTableButtons(v);
            v.normalBtns = normal;
            v.popoverBtns = popover;
          });
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },
    //事件派发
    eventDispacth(eventName, params = {}) {
      if (!eventName) {
        return;
      }
      this[eventName](params);
    },
    //校验下发按钮是否展示
    filterTableButtons(row) {
      // 处理
      let buttons = [];
      let result = {};
      let emuSource = {
        zlxz: [{ label: "资料下载", event: "dataDownload" }],
        fbkh: [{ label: "发布考核", event: "release" }],
        rwpz: [{ label: "任务配置", event: "gotoTaskConfig" }],
        view: [{ label: "查看", event: "gotoDetail" }],
        edit: [{ label: "编辑", event: "gotoEdit" }],
        del: [{ label: "删除", event: "handleDelClick" }],
      };
      Object.keys(emuSource).forEach((key) => {
        if (row[key] == true) {
          buttons = buttons.concat(emuSource[key]);
        }
      });
      if (buttons.length > 3) {
        const middle = 2;
        result = {
          normal: buttons.slice(0, middle),
          popover: buttons.slice(middle, buttons.length),
        };
      } else {
        result = {
          normal: buttons,
          popover: [],
        };
      }
      return result;
    },
    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    //校验状态名称
    checkStatusName(row) {
      let { taskStatus } = row;
      switch (taskStatus) {
        case 0:
          return "待发布";

        case 1:
          return "资料提交";

        case 2:
          return "待评分";

        case 3:
          return "已完成";

        default:
          return "--";
      }
    },

    //校验状态className
    checkStatusClass(row) {
      let { taskStatus } = row;
      switch (taskStatus) {
        case 0:
          return "cancel";

        case 1:
          return "warn";

        case 2:
          return "lock";

        case 3:
          return "normal";

        default:
          return "cancel";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  .status-text {
    border-radius: 4px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    font-size: 12px;
    width: 80px;
    &.normal {
      background: #4bc964;
    }
    &.warn {
      background: #ff993f;
    }
    &.lock {
      background: #0098ff;
    }
    &.cancel {
      background: #f1f2f7;
      color: #aab0bc;
    }
  }
}

/deep/.ant-popover {
  &.table-more-btns-popover {
    .ant-popover-inner-content {
      cursor: pointer;
      text-align: center;
      padding: 10px 0;
      .popover-btn {
        height: 30px;
        padding: 0 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        margin-bottom: 10px;
        color: #525a5d;
        &:last-child {
          margin: 0;
        }
        &:hover {
          background: #e9ecf3;
          color: @primary-color;
        }
      }
    }
  }
}
</style>
